package com.atguigu.lease.web.api.service.impl;

import com.atguigu.lease.model.base.BaseSearchDto;
import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.model.entity.GraphInfo;
import com.atguigu.lease.web.api.interceptor.StgyApiAuthInpterceptor;
import com.atguigu.lease.web.api.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.api.mapper.GraphInfoMapper;
import com.atguigu.lease.web.api.service.BrowsingHistoryService;
import com.atguigu.lease.web.api.vo.HistoryItemVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper , BrowsingHistory>
        implements BrowsingHistoryService {
    @Resource
    GraphInfoMapper graphInfoMapper;
    @Async
    @Override
    public void saveOrUpdateAsync(Long userId, Long roomId) {
        BrowsingHistory browsingHistory = this.getOne(Wrappers.lambdaQuery(BrowsingHistory.class)
                .eq(BrowsingHistory::getRoomId, roomId)
                .eq(BrowsingHistory::getUserId, userId)
                .last("limit 1"));
        if(browsingHistory == null){
            browsingHistory = new BrowsingHistory();
            browsingHistory.setRoomId( roomId);
            browsingHistory.setUserId( userId);
        }
        //设置浏览器时间
        browsingHistory.setBrowseTime(new Date());

        this.saveOrUpdate(browsingHistory);
    }

    @Override
    public Page<HistoryItemVo> pageItem(BaseSearchDto searchDto) {
        //分页查询 1对多 需要分步
        Page<HistoryItemVo> page = searchDto.getPage(HistoryItemVo.class);
        //需要使用会员id查询他自己的浏览器记录
        List<HistoryItemVo> historyItemVos =  baseMapper.selectPageItem( page ,
                StgyApiAuthInpterceptor.THREAD_LOCAL.get().getId());
        //查询每个浏览器记录的房间图片列表
        historyItemVos.forEach(historyItemVo -> {
            //查询每个浏览器记录的房间图片
            List<GraphInfo> graphInfos = graphInfoMapper.selectByRoomId(historyItemVo.getRoomId());
            historyItemVo.setRoomGraphVoList(graphInfos);
        });


        page.setRecords(historyItemVos);
        return page;
    }
}
